#include <iostream>
#include <string>
#include <memory>
#include <unistd.h>
#include "Log.hpp"
#include "Socket.hpp"

// ./server localport
int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        std::cout << "Usage: " << argv[0] << "port" << std::endl;
        return 0;
    }
    uint16_t localport = std::stoi(argv[1]);

    std::unique_ptr<TcpSocket> tsvr(new TcpSocket());
    tsvr->BuildListenSocketMethod(localport, backlog);
    while(true)
    {
        std::string peerip;
        uint16_t peerport;
        lg.LogMessage(Debug, "ready to accept, listensocketfd: %d\n", tsvr->GetSockFd());
        Socket *newsock = tsvr->AcceptConnection(&peerip, &peerport);
        if(newsock == nullptr) continue;
        lg.LogMessage(Info, "get a new link... sockfd: %d, client info: %s:%d\n", newsock->GetSockFd(), peerip.c_str(), peerport);
        
        while(true)
        {
            std::string buffer;
            newsock->Recv(&buffer, 1024);
            std::cout << "get a message: " << buffer.c_str() << std::endl;
            sleep(1);
        }

        // 注意资源的释放
        newsock->CloseSocket();
        delete newsock;
    }

    tsvr->CloseSocket();
    return 0;
}